package com.boy.rpc.framework.console.security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.codec.binary.Base64;

/**
 * Created by wesley on 2017-03-13.
 */
public class WwwAuthFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(WwwAuthFilter.class);

    private static final String AUTH_PREFIX = "Basic ";

    private String username = "root";

    private String password = "root";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + System.getProperty("file.separator") + filterConfig.getInitParameter("auth-config");
        //logger.debug("configFilePath -> :"+configFilePath);
        Properties props = new Properties();
        InputStream in = WwwAuthFilter.class.getResourceAsStream("/auth.properties");//从配置文件中读取
        try {
            //props.load(new FileInputStream(configFilePath));
            props.load(in);
        } catch (final IOException ex) {
            logger.warn("Cannot found auth config file, use default auth config.");
        }
        username = props.getProperty("console.username", username);
        password = props.getProperty("console.password", password);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        String authorization = httpRequest.getHeader("authorization");
        if (null != authorization && authorization.length() > AUTH_PREFIX.length()) {
            authorization = authorization.substring(AUTH_PREFIX.length(), authorization.length());
            if ((username + ":" + password).equals(new String(Base64.decodeBase64(authorization)))) {
                authenticateSuccess(httpResponse);
                filterChain.doFilter(httpRequest, httpResponse);
            } else {
                needAuthenticate(httpRequest, httpResponse);
            }
        } else {
            needAuthenticate(httpRequest, httpResponse);
        }
    }

    private void authenticateSuccess(final HttpServletResponse response) {
        response.setStatus(200);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
    }

    private void needAuthenticate(final HttpServletRequest request, final HttpServletResponse response) {
        response.setStatus(401);
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
        response.setHeader("WWW-authenticate", AUTH_PREFIX + "Realm=\"Boy Rpc Console Auth\"");
    }

    @Override
    public void destroy() {

    }
}
